#include "globalkey.h"
#include <QDebug>

GlobalKey::GlobalKey(QObject *parent) : QObject{parent}
{

}

void GlobalKey::RegisterKey(QString objectName, QList<QKeySequence> shortcut)
{
    if (m_pAction != nullptr)
    {
        qDebug()<<tr("shortcut key already create");
        return;
    }

    m_pAction = new QAction(this);
    m_pAction->setText("Screencap-"+(objectName));
    m_pAction->setObjectName(objectName);
    //when shortcut key had changed must restart kglobalaccel5
    m_pAction->setProperty("compoentName", QStringLiteral("KylinScreencapAction"));
    qDebug()<<tr("check has:")<<KGlobalAccel::self()->hasShortcut(m_pAction);

    KGlobalAccel::self()->setShortcut(m_pAction, shortcut);
    KGlobalAccel::self()->setDefaultShortcut(m_pAction, shortcut);
    qDebug()<<"key register successful.";

    connect(m_pAction, &QAction::triggered, this, [this](){
       qDebug()<<"注册的shutkey快捷键被触发";
       emit sigKeyTriggered();
    });

}

void GlobalKey::UnregisterKey()
{
    if(m_pAction == nullptr)
    {
       return;
    }

    if (KGlobalAccel::self()->hasShortcut(m_pAction))
    {
        qDebug() << tr("ready unregister it");
        KGlobalAccel::self()->removeAllShortcuts(m_pAction);
        delete m_pAction;
        m_pAction = nullptr;
    }
    else
    {
        qDebug()<<tr("can't find..the key")<<m_pAction->objectName();
    }
}
